#define _CRT_SECURE_NO_WARNINGS 1

#include"SList.h"



void SListNodePrint(SLTNode* phead)
{
	while (phead)
	{
		printf("%d->", phead->date);
		phead = phead->next;
	}
	printf("NULL\n");
}


SLTNode* BuySListNode(SLDateType x)
{
	SLTNode* newhead = (SLTNode*)malloc(sizeof(SLTNode));
	if (newhead == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	else
	{
		newhead->date = x;
		newhead->next = NULL;
		return newhead;
	}
}


void SListNodePushBack(SLTNode** pphead, SLDateType x)
{
	SLTNode* newhead = BuySListNode(x);
	if (*pphead == NULL)
	{
		*pphead = newhead;
	}
	else
	{
		SLTNode* tail = *pphead;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = newhead;
	}
}


void SListNodePushFront(SLTNode** pphead, SLDateType x)
{
	SLTNode* newhead = BuySListNode(x);
	newhead->next = *pphead;
	*pphead = newhead;
}



void SListNodePopBack(SLTNode** pphead)
{
	if (*pphead==NULL)
	{
		return;
	}
	else if ((*pphead)->next==NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* tail = *pphead;
		while (tail->next->next)
		{
			tail = tail->next;
		}
		tail->next = NULL;
		free(tail->next);
	}
}



void SListNodePopFront(SLTNode** pphead)
{
	if (*pphead == NULL)
	{
		return;
	}
	else
	{
		SLTNode* next = (*pphead)->next;
		free(*pphead);
		*pphead = next;
	}
}



SLTNode* SListFind(SLTNode* phead, SLDateType x)
{
	while (phead)
	{
		if (phead->date == x)
			return phead;
		phead = phead->next;
	}
	return NULL;
}



void SListNodeInsert(SLTNode** pphead, SLTNode* pos, SLDateType x)
{
	if (pos == *pphead)
	{
		SListNodePushFront(pphead, x);
	}
	else
	{
		SLTNode* newhead = BuySListNode(x);
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = newhead;
		newhead->next = pos;
	}
}


void SListNodeErase(SLTNode** pphead, SLTNode* pos)
{
	if (pos == *pphead)
	{
		SListNodePopFront(pphead);
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
	}
}